package cn.zebra.dev.mall.module.weixinPay.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.mall.module.weixinPay.util.AuthUtil;
import cn.zebra.dev.mall.module.weixinPay.util.CertHttpUtil;
import cn.zebra.dev.order.module.order.entity.OrdersEntity;
import cn.zebra.dev.order.module.order.service.OrdersService;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@RestController
@Api(tags = "申请退款")
@RequestMapping("/orderRefundAuto")
public class RefundAutoOrdersController {

    @Autowired
    private OrdersService ordersService;

    @Value("${weixin.appid}")
    private String appid;         //微信公众账号或开放平台APP的唯一标识

    @Value("${weixin.mchid}")
    private String mchid;       //商户号

    @Value("${weixin.partnerkey}")
    private String partnerkey;    //商户密钥

    @Value("${weixin.apikey}")
    private String apikey;

    @Value("${weixin.refund}")
    private String refund;           //退款接口

    @Value("${weixin.notifyurl}")
    private String notifyurl;     // 回调地址


    @PostMapping("/weixinRefund")
    @ApiOperation("订单自动退款")
    public Result weixinRefund(@PathVariable Long id){
        //根据订单id查询商品具体信息
        OrdersEntity ordersEntity = ordersService.findById(id);
        if (ordersEntity==null){
            return Result.error("订单不存在");
        }
        int ordersStatus = ordersEntity.getOrdersStatus();
        if (ordersStatus == -1 || ordersStatus == 0){
            return Result.error("请先付款");
        }
        String nonce_str = WXPayUtil.generateNonceStr(); // 生成随机数
        //map集合
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid",appid);
        packageParams.put("mch_id", mchid); // 商务号
        packageParams.put("nonce_str", nonce_str); // 随机生成后数字，保证安全性
        packageParams.put("out_trade_no",ordersEntity.getOrdersSn()); //商户订单号
        packageParams.put("out_refund_no",ordersEntity.getOrdersSn()); //退款单号
        packageParams.put("total_fee",String.valueOf(ordersEntity.getTotalPrice()));//订单金额
        packageParams.put("refund_fee",String.valueOf(ordersEntity.getTotalPrice()));//退货金额

        try {
            //生成签名
            String sign = WXPayUtil.generateSignature(packageParams,apikey);
            //将签名再放回map中，它也是一个参数
            packageParams.put("sign",sign);
            //将当前的map结合转化成xml格式
            String xml = WXPayUtil.mapToXml(packageParams);
            //获取需要发送的url地址,向微信发送请求转账请求
            String returnXml = CertHttpUtil.postData(refund, xml, mchid, AuthUtil.CERTPATH);
            //将微信返回的xml结果转成map格式
            Map<String, String> returnMap = WXPayUtil.xmlToMap(returnXml);
            if (returnMap.get("return_code").equals("SUCCESS")) {
                // 退款成功
                System.out.println("returnMap为:" + returnMap);
                return Result.success(returnMap);
            }
            return Result.error(returnXml);

        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.error("退款失败");
    }

}
